package person;

import io.vertx.config.ConfigRetriever;
import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import servicediscovery.RestAPIVerticle;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.fail;

/**
 * @Author Ldj
 * @Date 2017/11/2 15:39
 * @Description 数据处理
 */
public class PersonAPIVerticle extends RestAPIVerticle {

    private static final String API_GETPERSON = "/person/:personId";
    private static final String API_ADDPERSON = "/sperson/:personId";
    //private static final String API_RETRIEVE = "/:productId";

    private PersonService personService;

    private Map<String,JsonObject> personListMap = new HashMap();

    @Override
    public void start(Future<Void> future) throws Exception {
        super.start();
        /*ConfigRetriever retriever = ConfigRetriever.create(vertx,
                new ConfigRetrieverOptions().addStore(
                        new ConfigStoreOptions()
                                .setType("file")
                                .setFormat("properties")
                                .setConfig(new JsonObject().put("path", "application.properties"))));
        retriever.getConfig(ar -> {
            if(ar.succeeded()){
                JsonObject config = ar.result();
            }
            else {
                ar.cause().printStackTrace();
                fail("Failure unexpected: " + ar.cause().getMessage());
            }
        });
        retriever.listen(change -> {
            // Previous configuration
            JsonObject previous = change.getPreviousConfiguration();
            // New configuration
            JsonObject conf = change.getNewConfiguration();
        });*/


        this.personService = PersonService.createService(vertx, config());
        //this.inventoryService = InventoryService.createService(vertx, config());
        setUpInitialData();
        //personService = new PersonServiceImpl(vertx, config());
        final Router router = Router.router(vertx);
        // body handler
        router.route().handler(BodyHandler.create());
        // API handler
        router.get(API_GETPERSON).handler(this::apiGetPerson);
        router.get(API_ADDPERSON).handler(this::apiAddPerson);


        createHttpServer(router, "localhost", 8086)
                .compose(serverCreated -> publishHttpEndpoint("person", "localhost", 8086, "/"))
                .setHandler(future.completer());
    }

    //测试基本数据匹配
    private void apiGetPerson(RoutingContext routingContext) {
        String personId = routingContext.request().getParam("personId");
        HttpServerResponse response = routingContext.response();
        if (personId == null) {
            //response.setStatusCode(400).end();
            sendError(400, response);
        } else {
            JsonObject product = personListMap.get(personId);
            if (product == null) {
                sendError(404, response);
            } else {
                response.putHeader("content-type", "application/json").end(product.encodePrettily());
            }
        }
    }

    //测试mysql 连接
    private void apiAddPerson(RoutingContext routingContext) {
        String personId = routingContext.request().getParam("personId");
        personService.apiAddPerson(vertx,personId)
                .setHandler(rawResultHandler(routingContext));
    }

    //初始化人员数据
    private void setUpInitialData() {
        addPerson(new JsonObject().put("id", "1").put("name", "张三").put("age", 18).put("weight", 150));
        addPerson(new JsonObject().put("id", "2").put("name", "李四").put("age", 20).put("weight", 100));
        addPerson(new JsonObject().put("id", "3").put("name", "王五").put("age", 22).put("weight", 80));
    }

    private void addPerson(JsonObject person) {
        personListMap.put(person.getString("id"), person);
    }

    private void sendError(int statusCode, HttpServerResponse response) {
        response.setStatusCode(statusCode).end();
    }

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(PersonAPIVerticle.class.getName());
    }
}
